import OpenAI from "openai";
import { AI_PROVIDERS, PROVIDER_ICONS } from "./models-data";

export type ModelType =
	| "text"
	| "vision"
	| "embedding"
	| "reasoning"
	| "function_calling"
	| "web_search";

export type Model = {
	id: string;
	provider: string;
	name: string;
	group: string;
	owned_by?: string;
	description?: string;
	type?: ModelType[];
	enabled?: boolean;
};

export type Provider = {
	id: string;
	name: string;
	apiKey: string;
	apiHost: string;
	apiVersion?: string;
	models: Model[];
	enabled: boolean;
	isSystem?: boolean;
	isAuthed?: boolean;
	rateLimit?: number;
	isNotSupportArrayContent?: boolean;
	isVertex?: boolean;
	notes?: string;
	extra_headers?: Record<string, string>;
};

export type ChatContent = {
	content: string;
	stream: boolean;
	onMessage: (chunk: string) => void;
	onFinish: () => void;
	onError: (error: Error) => void;
};

type LocalInfo = {
	currentProvider: string;
	currentModel: string;
	configs: Record<string, { apiKey: string; enabled: boolean }>;
};

const saveConfigKey = "ai-core-config";

class AiCore {
	private _providers: Provider[] = [];
	private _currentModel: Model | null = null;
	private _currentProvider: Provider | null = null;
	private _openaiInstances: Map<string, OpenAI> = new Map();

	constructor() {}

	/**
	 * 加载供应商配置
	 */
	async loadProviders(): Promise<void> {
		const localData = await this.loadFromStorage();
		if (!localData) {
			this._providers = AI_PROVIDERS.map((provider) => ({
				...provider,
				apiKey: "",
				enabled: false,
			}));
			this._currentProvider = null;
			this._currentModel = null;
			return;
		}
		this._providers = AI_PROVIDERS.map((provider) => ({
			...provider,
			apiKey: localData.configs[provider.id]?.apiKey || "",
			enabled: localData.configs[provider.id]?.enabled || false,
		}));

		if (this.enabledProviders.length === 0) {
			this._currentProvider = null;
			this._currentModel = null;
			return;
		}
		this._currentProvider =
			this.enabledProviders.find((p) => p.id === localData.currentProvider) ||
			this.enabledProviders[0];
		this._currentModel =
			this._currentProvider?.models.find(
				(m) => m.id === localData.currentModel
			) || this._currentProvider.models[0];
	}

	/**
	 * 生成存储数据
	 * {
	 * 	currentProvider: string;
	 * 	currentModel: string;
	 * 	configs: {
	 * 		providerName: {
	 * 			apiKey: string;
	 * 			enabled: boolean;
	 * 		}
	 * 	}
	 * }
	 */
	_getSaveConfig(): LocalInfo {
		return {
			currentProvider: this._currentProvider?.id || "",
			currentModel: this._currentModel?.id || "",
			configs: this._providers
				.filter((provider) => provider.apiKey && provider.enabled)
				.reduce((acc, provider) => {
					acc[provider.id] = {
						apiKey: provider.apiKey,
						enabled: provider.enabled,
					};
					return acc;
				}, {} as Record<string, { apiKey: string; enabled: boolean }>),
		};
	}

	/**
	 * 获取所有供应商
	 */
	get providers(): Provider[] {
		return this._providers;
	}

	/**
	 * 获取启用的供应商
	 */
	get enabledProviders(): Provider[] {
		return this._providers.filter((p) => p.enabled);
	}

	/**
	 * 获取当前供应商
	 */
	get currentProvider(): Provider | null {
		return this._currentProvider;
	}
	/**
	 * 获取当前模型
	 */
	get currentModel(): Model | null {
		return this._currentModel;
	}
	/**
	 * 获取当前供应商的图标
	 */
	get currentProviderIcon(): string {
		return this._currentProvider
			? PROVIDER_ICONS[this._currentProvider.id] || ""
			: "";
	}

	/**
	 * 设置当前供应商
	 */
	setCurrentProvider(providerId: string): boolean {
		const provider = this._providers.find((p) => p.id === providerId);
		if (provider && provider.enabled) {
			this._currentProvider = provider;
			return true;
		}
		return false;
	}

	/**
	 * 设置当前模型
	 */
	setCurrentModel(model: Model): boolean {
		const provider = this._providers.find((p) => p.id === model.provider);
		if (provider && provider.enabled) {
			this._currentProvider = provider;
			const res = this._currentProvider?.models.find((m) => m.id === model.id);
			if (res) {
				this._currentModel = res;
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取所有模型
	 */
	get models(): Model[] {
		return this._providers.flatMap((provider) =>
			provider.models.map((model) => ({
				...model,
				provider: provider.id,
				enabled: provider.enabled,
			}))
		);
	}

	/**
	 * 获取启用的模型
	 */
	get enabledModels(): Model[] {
		return this.models.filter((model) => model.enabled);
	}

	/**
	 * 获取指定供应商的模型
	 */
	getModelsByProvider(providerId: string): Model[] {
		const provider = this._providers.find((p) => p.id === providerId);
		return provider?.models.filter((m) => m.enabled) || [];
	}

	/**
	 * 更新供应商配置
	 */
	updateProvider(providerData: Provider): void {
		const index = this._providers.findIndex((p) => p.id === providerData.id);
		if (index >= 0) {
			this._providers[index] = { ...providerData };

			// 如果更新的是当前供应商，更新引用
			if (this._currentProvider?.id === providerData.id) {
				this._currentProvider = this._providers[index];
			}

			// 清除对应的OpenAI实例缓存
			this._openaiInstances.delete(providerData.id);

			console.log("AiCore: 已更新供应商配置", providerData.name);

			this.saveToStorage();
		}
	}

	/**
	 * 获取或创建OpenAI实例
	 */
	getOpenAI(providerId?: string): OpenAI | null {
		const provider = providerId
			? this._providers.find((p) => p.id === providerId)
			: this._currentProvider;

		if (!provider || !provider.enabled) {
			return null;
		}

		// 检查缓存
		if (this._openaiInstances.has(provider.id)) {
			return this._openaiInstances.get(provider.id)!;
		}

		// 创建新的OpenAI实例
		const openai = new OpenAI({
			apiKey: provider.apiKey,
			baseURL: provider.apiHost,
			dangerouslyAllowBrowser: true,
			// ...(provider.extra_headers && {
			// 	defaultHeaders: provider.extra_headers,
			// }),
		});

		this._openaiInstances.set(provider.id, openai);
		return openai;
	}

	/**
	 * 发送请求
	 */
	async sendChat(content: ChatContent) {
		try {
			const openai = this.getOpenAI();
			if (!openai) {
				throw new Error("无法获取AI服务实例，请检查供应商配置");
			}
			if (!this._currentModel) {
				throw new Error("无法获取当前模型，请检查供应商配置");
			}

			const response = await openai.chat.completions.create({
				model: this._currentModel.id,
				messages: [
					{ role: "system", content: "" },
					{ role: "assistant", content: "" },
					{ role: "user", content: content.content },
				],
				stream: content.stream,
			});
			if (content.stream) {
				const streamResult =
					response as AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>;
				let fullAnswer = "";
				let fullReasoning = "";
				for await (const chunk of streamResult) {
					const delta = chunk.choices[0].delta as {
						reasoning_content: string;
						content: string;
					};
					// 检查是否有reasoning_content
					if (delta.reasoning_content) {
						fullReasoning += delta.reasoning_content;
					}
					// 添加普通内容
					if (chunk.choices[0].delta.content) {
						fullAnswer += chunk.choices[0].delta.content;
					}
					// 封装
					let text = "";
					if (fullReasoning) {
						text = `<think>${fullReasoning}`;
						if (fullAnswer) {
							text += `</think>${fullAnswer}`;
						}
					} else {
						text = fullAnswer;
					}
					// 发送消息
					content.onMessage(text);

					// 检查是否完成
					if (chunk.choices[0].finish_reason == "stop") {
						content.onFinish();
					}
				}
			} else {
				const result = response as OpenAI.Chat.Completions.ChatCompletion;
				// 非流式响应
				if (result.choices[0].message.content) {
					content.onMessage(result.choices[0].message.content);
				}
				content.onFinish();
			}
		} catch (error) {
			content.onError(error as Error);
			content.onFinish();
		}
	}

	/**
	 * 验证ApiKey是否有效
	 */
	async verifyApiKey(provider: Provider): Promise<boolean> {
		try {
			const openai = new OpenAI({
				apiKey: provider.apiKey,
				baseURL: provider.apiHost,
				dangerouslyAllowBrowser: true,
			});

			// 发送一个简单的测试请求验证API Key
			const response = await openai.chat.completions.create({
				model: provider.models[0].id,
				messages: [{ role: "user", content: "Hello" }],
				max_tokens: 1,
			});

			return !!response;
		} catch (error) {
			return false;
		}
	}

	/**
	 * 保存配置到Chrome存储
	 */
	async saveToStorage(): Promise<void> {
		const config = this._getSaveConfig();

		try {
			if (chrome && chrome.storage) {
				await chrome.storage.sync.set({ [saveConfigKey]: config });
			} else {
				localStorage.setItem(saveConfigKey, JSON.stringify(config));
			}

			console.log("AiCore: 配置已保存到Chrome存储");
		} catch (error) {
			console.error("AiCore: 保存配置失败", error);
		}
	}

	/**
	 * 从Chrome存储加载配置
	 */
	async loadFromStorage(): Promise<LocalInfo> {
		let data;
		try {
			// 判断当前环境：检查是否存在chrome.runtime
			if (
				typeof chrome !== "undefined" &&
				chrome.runtime &&
				chrome.runtime.id
			) {
				// 浏览器插件环境，使用chrome.storage API
				const result = await chrome.storage.sync.get(saveConfigKey);
				data = result[saveConfigKey];
			} else {
				// 网页环境，使用localStorage
				const storedConfig = localStorage.getItem(saveConfigKey);
				data = storedConfig ? JSON.parse(storedConfig) : null;
			}
		} catch (error) {
			console.error("AiCore: 加载配置失败", error);
		} finally {
			return data as LocalInfo;
		}
	}

	/**
	 * 重置为默认配置
	 */
	resetToDefaults(): void {
		this.loadProviders();
		this._openaiInstances.clear();
		localStorage.removeItem("ai-core-config");
		console.log("AiCore: 已重置为默认配置");
	}
}

export default AiCore;

// 导出预定义的模型和供应商数据
export * from "./models-data";
